package map.android.baidu.carpool.setting;

import android.content.Context;
import android.telephony.TelephonyManager;
import com.baidu.components.api.extra.APIProxy;
import com.baidu.mapframework.api.ComAPIManager;
import com.baidu.mapframework.common.util.WebViewConst;
import com.baidu.mapframework.component.ComConstant;
import com.baidu.mapframework.component.comcore.exception.ComException;
import com.baidu.mapframework.component.comcore.impl.message.DefaultComRequestFactory;
import com.baidu.mapframework.component.comcore.impl.message.params.ComBaseParams;
import com.baidu.mapframework.component.comcore.manager.ComponentManager;
import com.baidu.mapframework.component.comcore.message.ComParams;
import com.baidu.mapframework.component.comcore.message.ComRequest;
import com.baidu.mapframework.component.comcore.message.ComResponse;
import com.baidu.mapframework.component.comcore.message.ComResponseHandler;
import com.baidu.mapframework.location.LocationChangeListener.CoordType;
import com.baidu.mapframework.location.LocationManager;
import com.baidu.mapframework.location.LocationManager.LocData;
import map.android.baidu.carpool.model.CarpoolPosition;

import java.util.HashMap;

/**
 * 项目中用户信息,地图跳转其他组件的方法及设备信息的封装
 */
public class UserInfoSetting {
    /** 通过open api 活动页面跳转  获取src_from*/
    public static final String KEY_PARAM = "param";
    public static final String KEY_LDATA = "ldata";
    public static final String KEY_QID = "qid";
    
	private static String sub_from ;
	private static String cImei = "";
	private static String qid = "";
	private static String src_from ="";
	
	public static String getSrc_from() {

        return src_from;
    }

    public static void setSrc_from(String srcFrom) {

        src_from = srcFrom;
    }

    public static void setQid(String q_id) {

        qid = q_id;
    }

    public static String getQid() {

        return qid;
    }
	
	
	public static void setSubFrom(String s) {

        sub_from = s;
	}

	public static String getSubFrom() {

        return sub_from;
	}

	public static String getRequestFrom() {

        return "client";
	}

    public static  String getMb() {
        String deviceName = ComAPIManager.getComAPIManager().getSystemAPI().getDeviceName();
        return deviceName.replace(" ", "%20");
    }


    public static String getSv() {
        return ComAPIManager.getComAPIManager().getSystemAPI().getAppVersion();
    }

    public static String getChannel() {
        return ComAPIManager.getComAPIManager().getSystemAPI().getChannel();
    }

	public static String getV() {
		//TODO 根据后端项目要求制定版本
        return "";
	}

//	public static void handleThirdPartyLogin(Activity activity, final ILoginHandler loginHandler) {
//		OkCancelDialog.showDialog(activity, "提示", "您使用了第三方账号登录到百度，需要您使用百度账号进行登陆，是否退出当前登陆后使用百度账号登陆？", "是", "否",
//                new OnClickListener() {
//
//                    @Override
//                    public void onClick(View v) {
//                        if (!NetworkUtils.checkNetworkStatus(true)) {
//                            loginHandler.onLoginFailed();
//                            return;
//                        }
//                        logout();
//                        gotoSmsLogin(loginHandler);
//                    }
//                });
//	}

	public static boolean isLogin() {
		return APIProxy.settings().isLogin();
	}

	public static void logout() {
		DefaultComRequestFactory factory = new DefaultComRequestFactory();
		ComRequest request = factory.newComRequest(ComConstant.COM_CATEGORY_MAIN_MAP, ComRequest.METHOD_INVOKE);
		ComBaseParams parameters = new ComBaseParams();

		parameters.setTargetParameter("invoke_logout");
		request.setParams(parameters);
		try {
			ComponentManager.getComponentManager().invoke(request);
		} catch (ComException e) {
			e.printStackTrace();
		}
	}

	public static void gotoSmsLogin(final ILoginHandler loginHandler) {
		ComResponseHandler<Object> handler = new ComResponseHandler<Object>() {

			@Override
			public Object handleResponse(ComResponse arg0) {
				if (loginHandler != null) {
					if (isLogin()) {
						loginHandler.onLoginSucceed();
					} else {
						loginHandler.onLoginFailed();
					}
				}
				return null;
			}
		};
		launchLoginWithoutThirdPart(handler);
		// APIProxy.settings().goToSmsLogin(handler);
	}

	public static String getImei() {
		Context context = APIProxy.res().getBaseActivity();
        if (context == null) {
            return "";
        }
        if (cImei == null || cImei.length() == 0) {
        	cImei = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        }
        return cImei;
    }
	
	public static String getBduss() {
		// return BDUSS;
		return APIProxy.settings().getBDUSS();
	}

	public static String getMapLevel() {
		return APIProxy.map().getMapLevel() + "";
	}

	public static String getCuid() {
		return APIProxy.sys().getCuid();
	}

	public static String getProductType() {
		return "1";
	}

	public static String getOS() {
		return APIProxy.sys().getOsName();
	}

	public static String getOSVersion() {
		return APIProxy.sys().getOsVersion();
	}

	public static String getCityId() {
			return Integer.toString(APIProxy.settings().getLocationCityId());
	}

	public static String getCityName() {
		return APIProxy.settings().getLocationCityName();
	}

	public static LocData getCurrentLocation() {
		return APIProxy.settings().getCurrentLocation(CoordType.CoordType_BD09);
	}

	public static double getBaiduMocLng() {
		try {
			LocationManager.LocData locData = LocationManager.getInstance().getCurLocation(null);
			return locData.longitude;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static double getBaiduMocLat() {
		try {
			LocationManager.LocData locData = LocationManager.getInstance().getCurLocation(null);
			return locData.latitude;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	private static void launchLoginWithoutThirdPart(ComResponseHandler<Object> handler) {
		DefaultComRequestFactory factory = new DefaultComRequestFactory();
		ComRequest request = factory.newComRequest("mainmap", ComRequest.METHOD_QUERY);
		ComBaseParams parameters = new ComBaseParams();

		parameters.setTargetParameter("request_login_info");
		parameters.putBaseParameter("third_login_enable", false);
		parameters.putBaseParameter("login_page", "sms_login");
		request.setParams(parameters);
		try {
			ComponentManager.getComponentManager().request(request, handler);
		} catch (ComException e) {
			e.printStackTrace();
		}
	}

	public static void bindPhone() {
		StringBuilder url = new StringBuilder();
		// 线上环境
		url.append("http://i.map.baidu.com/api/page/verify/mobile?");

		// QA联调环境
		// url.append("http://db-testing-local01.db01.baidu.com:8086/api/page/verify/mobile?");

		// 开发环境
		// url.append("http://cq01-rdqa-dev064.cq01.baidu.com:8091/api/page/verify/mobile?");

		url.append("jurl=");
		url.append("bdapi://taxiBindSuccess");

		url.append("&bduss=");
		url.append(ComAPIManager.getComAPIManager().getSettingsAPI().getBDUSS());

		url.append("&mb=");
		url.append(ComAPIManager.getComAPIManager().getSystemAPI().getDeviceName());

		url.append("&os=");
		url.append(ComAPIManager.getComAPIManager().getSystemAPI().getOsName());

		url.append("&sv=");
		url.append(ComAPIManager.getComAPIManager().getSystemAPI().getAppVersion());

		url.append("&net=");
		url.append(ComAPIManager.getComAPIManager().getSystemAPI().getNetworkType());

		url.append("&resid=");
		url.append(ComAPIManager.getComAPIManager().getSystemAPI().getResId());

		url.append("&cuid=");
		url.append(ComAPIManager.getComAPIManager().getSystemAPI().getCuid());

		url.append("&channel=");
		url.append(ComAPIManager.getComAPIManager().getSystemAPI().getChannel());

		url.append("&screen=");
		url.append("(" + ComAPIManager.getComAPIManager().getSystemAPI().getScreenWidth() + ","
				+ ComAPIManager.getComAPIManager().getSystemAPI().getScreenHeight() + ")");

		url.append("&dpi=");
		url.append("(" + ComAPIManager.getComAPIManager().getSystemAPI().getScreenXDpi() + ","
				+ ComAPIManager.getComAPIManager().getSystemAPI().getScreenYDpi() + ")");

		url.append("&ver=");
		url.append(ComAPIManager.getComAPIManager().getSystemAPI().getOsVersion());

		url.append("&ctm=1386838081.576000");

		url.append("&loc=");

		url.append("&c=");

		DefaultComRequestFactory factory = new DefaultComRequestFactory();
		ComRequest request = factory.newComRequest("mainmap", ComRequest.METHOD_DISPATCH);
		ComBaseParams parameters = new ComBaseParams();
		parameters.setTargetParameter("user_center_webview_page");

		parameters.putBaseParameter("webview_url", url.toString());
		parameters.putBaseParameter("webview_title", "更换手机号");

		request.setParams(parameters);
		try {
			ComponentManager.getComponentManager().dispatch(request);
		} catch (ComException e) {

		}

	}

	public static void share(String title, String content) {

		DefaultComRequestFactory factory = new DefaultComRequestFactory();
		ComRequest request = factory.newComRequest("mainmap", ComRequest.METHOD_DISPATCH);
		ComParams params = new ComBaseParams();
		params.setTargetParameter("social_share");
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("title", title);
		map.put("content", content);
		// map.put("img_path", "file:/" + filePath.toString());
		params.setBaseParameters(map);
		request.setParams(params);

		try {
			ComponentManager.getComponentManager().dispatch(request);
		} catch (ComException e) {

		}
	}

	public static void goToWebShell(String url) {
        DefaultComRequestFactory factory = new DefaultComRequestFactory();
        ComRequest request = factory.newComRequest("mainmap", ComRequest.METHOD_DISPATCH);
        ComBaseParams params = new ComBaseParams();
        params.setTargetParameter("web_shell_page");
        params.putBaseParameter(WebViewConst.WEBVIEW_URL_KEY, url);
        params.putBaseParameter(WebViewConst.WEBSHELL_IS_SHARE_SHOW, false);
        params.putBaseParameter(WebViewConst.WEBSHELL_IS_BOTTOM_DISPLAY, false);
        request.setParams(params);
        try {
            ComponentManager.getComponentManager().dispatch(request);
        } catch (ComException e) {
            e.printStackTrace();
        }
    }

    public static void goToWebShell(String url,String title) {
        DefaultComRequestFactory factory = new DefaultComRequestFactory();
        ComRequest request = factory.newComRequest("mainmap", ComRequest.METHOD_DISPATCH);
        ComBaseParams params = new ComBaseParams();
        params.setTargetParameter("web_shell_page");
        params.putBaseParameter(WebViewConst.WEBVIEW_URL_KEY, url);
        params.putBaseParameter(WebViewConst.WEBSHELL_IS_SHARE_SHOW, false);
        params.putBaseParameter(WebViewConst.WEBSHELL_IS_BOTTOM_DISPLAY, false);
        params.putBaseParameter(WebViewConst.WEBVIEW_TITLE_KEY, title);
        request.setParams(params);
        try {
            ComponentManager.getComponentManager().dispatch(request);
        } catch (ComException e) {
            e.printStackTrace();
        }
    }

	public static interface ILoginHandler {
		public void onLoginSucceed();

		public void onLoginFailed();
	}

    //经纬度转墨卡托
    public static CarpoolPosition lonLat2Mercator(CarpoolPosition lonLat) {
        CarpoolPosition mercator = new CarpoolPosition();
        double x = lonLat.x * 20037508.34 / 180;
        double y = Math.log(Math.tan((90 + lonLat.y) * Math.PI / 360)) / (Math.PI / 180);
        y = y * 20037508.34 / 180;
        mercator.x = x;
        mercator.y = y;
        return mercator;
    }
    //墨卡托转经纬度
    public static CarpoolPosition Mercator2lonLat(CarpoolPosition mercator) {
        CarpoolPosition lonLat = new CarpoolPosition();
        double x = mercator.x  / 20037508.34 * 180;
        double y = mercator.y / 20037508.34 * 180;
        y = 180 / Math.PI * (2 * Math.atan(Math.exp(y * Math.PI / 180)) - Math.PI / 2);
        lonLat.x = x;
        lonLat.y = y;
        return lonLat;
    }

}
